﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using MiniCrawler.DataAccess;
using MiniCrawler.DataAccess.Repositories;
using MiniCrawler.Downloader.ResourceDownloader;
using MiniCrawler.Entity;
using MiniCrawler.UrlFilter;

namespace MiniCrawler.Downloader.ResourceDownloader
{
    public class ModCloth : ResourceLinkCollector,IResourceCollector
    {
        private string hostName;

        public ModCloth(string hostName, int level): base(hostName, level)
        {
            this.hostName = hostName;
        }

        public string GetFolderPath(string data)
        {
            // Load data
            var doc = new HtmlDocument();
            doc.LoadHtml(data);

            string xPathExpression = "/html/body[@class='gecko ff4 win']/div[@id='mc-1034']/div[@id='content']/div[@id='main-content']/div[@id='breadcrumbs']/ul";
            var node = doc.DocumentNode.SelectSingleNode(xPathExpression);

            string nodeInnerText = "/";
            if(node != null)
                nodeInnerText =  node.InnerText;

            // Processing text
            // \ / : | ? * "
            string processedText =
                nodeInnerText
                    .Replace("&gt;", ">")
                    .Replace("&raquo;", ">")
                    .Replace("&amp;", "-")
                    .Replace(">", "\\")
                    .Replace("»", "\\")
                    .Replace('&', '-')
                    .Replace("/", string.Empty)
                    .Replace("|", string.Empty)
                    .Replace("?", string.Empty)
                    .Replace("*", string.Empty)
                    .Replace("\"", string.Empty)
                    .Replace(":", string.Empty);
                
            

            if (!string.IsNullOrEmpty(processedText))
                return processedText;
            else return "/";
        }

        public List<string> GetAllLinks(string data)
        {
    var result = new List<string>();
    //        //string xPathExpression =
    //        //    "/html/body[@class='gecko ff4 win']/div[@id='mc-1034']/div[@id='content']/div[@id='main-content']/div[@class='product-detail-page ']/div[@id='image-container']/div[@id='product_main_image']/a[@id='zoomable']";

    //        string xPathExpression =
    //"/html/body[@class='gecko ff4 win']/div[@id='mc-1034']/div[@id='content']/div[@id='main-content']/div[@class='product-detail-page ']/div[@id='image-container']/div[@id='product_main_image']";


    //        var doc = new HtmlDocument();
    //        doc.LoadHtml(data);


    //        var node = doc.DocumentNode.SelectSingleNode(xPathExpression);
    //        if (node == null) return result;

    //        var t = node.Attributes["href"];

            List<string> allLinks = FindStringBetween(data, "hi_res_url", ",");


            string expressionObjectTemplate1 =
                "<Expression><ExpressionParts><Part><Command>StartOfLine</Command><Value></Value></Part><Part><Command>Then</Command><Value>http://</Value></Part><Part><Command>AnythingBut</Command><Value>/</Value></Part><Part><Command>Then</Command><Value>modcloth.net/</Value></Part><Part><Command>AnythingBut</Command><Value>*</Value></Part><Part><Command>Then</Command><Value>.jpg?</Value></Part><Part><Command>IsSequenseOfNumber</Command><Value></Value></Part><Part><Command>EndOfLine</Command><Value></Value></Part></ExpressionParts></Expression>";


            //http://productshots3.modcloth.net/productshots/0132/6935/c46b7ef15e997f85c3b156a6b4f73e61.jpg?1377893245

            ExpressionObject exp1 = new ExpressionObject(expressionObjectTemplate1);

            foreach (var link1 in allLinks)
            {
                var link = Common.FillAbsoluteUrl(hostName, link1);
                if(exp1.IsMatch(link))
                {
                    var z = link.Substring(0, link.LastIndexOf('?'));
                    result.Add(z);
                }
            }

            return result;
        }


        private List<string> FindStringBetween(string source, string start, string end)
        {
            var t = source.IndexOf(start);
            var result = new List<string>();

            while (t != null && t != -1)
            {
                string cutsource = source.Substring(t, source.Length - t);
                var z = cutsource.IndexOf(end);
                if (z != null && z != t)
                {
                    var s = cutsource.Substring(0, z);
                    cutsource = cutsource.Replace(s, string.Empty);
                    s = s.Substring(s.IndexOf("'"), s.Length - s.IndexOf("'"));
                    s = s.Replace("'", string.Empty);
                    result.Add(s);
                    source = cutsource;
                    t = source.IndexOf(start);
                }
            }

            return result;
        }

        public List<string> GetResourcePatterns()
        {
            return new List<string>();
        }

        public void GetLinks()
        {


            //string data1 = Common.GetWebPage("http://www.modcloth.com/shop/shoes-flats/shoes-of-note-flat");

            //string s = GetFolderPath(data1);

            //var z = GetAllLinks(data1);

            //return;
            foreach (var dataLink in Urls)
            {
                string data = Common.GetWebPage(Common.FillAbsoluteUrl(hostName, dataLink.Value));
                if(string.IsNullOrEmpty(data)) return; 

                string folderPath = GetFolderPath(data);

                var allLinks = GetAllLinks(data);

                if(allLinks != null && allLinks.Count > 0)
                {
                    foreach (var link in allLinks)
                    {
                        var downloadLink = 
                            new DownloadLink
                                {
                                    Path = folderPath,
                                    Value = link,
                                    Website = dataLink.Website,
                                    IsDownloaded = false
                                };
                        DownloadLinkHelper.CreateLink(downloadLink);
                    }
                }

                DataLinkHelper.UpdateLink(dataLink.Value);
            }
        }

        public void FixUrls()
        {
            DownloadLinkHelper.FixPathUrl(hostName);
        }
    }
}
